package com.study.system.edusearchservice.listener;

import com.alibaba.fastjson.JSON;
import com.edu.common.entity.Course;
import com.study.system.edusearchservice.service.CourseIndexService;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * 课程消息队列监听器
 */
@Configuration
public class CourseMQListener {

    public static final String QUEUE_UPDATE = "course-update-queue";
    public static final String QUEUE_DELETE = "course-delete-queue";
    public static final String EXCHANGE_COURSE = "course-exchange";
    public static final String KEY_UPDATE = "course-update-key";
    public static final String KEY_DELETE = "course-delete-key";

    @Resource
    private CourseIndexService courseIndexService;


    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = QUEUE_UPDATE,durable = "true"),
            exchange = @Exchange(value = EXCHANGE_COURSE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = KEY_UPDATE)})
    public void listenCourseUpdate(String course){
        System.out.println("要更新的课程：" + course);
        //将json转化为Course对象
        Course course1 = JSON.parseObject(course, Course.class);
        try {
            //更新课程索引
            courseIndexService.saveCourse(course1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = QUEUE_DELETE,durable = "true"),
            exchange = @Exchange(value = EXCHANGE_COURSE,type = ExchangeTypes.TOPIC,ignoreDeclarationExceptions = "true"),
            key = KEY_DELETE)})
    public void listenCourseDelete(String courseId){
        System.out.println("要删除的课程id:" + courseId);
        try {
            //删除课程
            courseIndexService.deleteCourse(Integer.valueOf(courseId));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
